<!-- 商品添加页 -->
<template>
  <div class="product-add-main">
    <!-- 步骤条 -->
    <div class="step-bar">
      <el-steps :active="active" finish-status="success">
        <el-step title="步骤 1"></el-step>
        <el-step title="步骤 2"></el-step>
        <el-step title="步骤 3"></el-step>
      </el-steps>
    </div>

    <!-- 表单内容 -->
    <el-card>
      <el-form :model="product" :rules="rules" ref="form" label-width="80px">
        <!-- 第一部分 -->
        <div class="step-first" v-show="active==0">
          <el-row>
            <el-col :span="8">
              <el-form-item label="商品名称" prop="gname">
                <el-input v-model="product.gname" size="small" class="input"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="品牌">
                <el-select size="small" v-model="product.brand_id" placeholder="请选择">
                  <el-option
                    v-for="item in brandListAll"
                    :key="item.id"
                    :label="item.cname"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="原产地">
                <el-cascader
                  size="small"
                  :options="options"
                  v-model="selectedCity"
                  @change="handleChange"
                  placeholder="原产地"
                ></el-cascader>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="商品编码">
                <el-input v-model="product.pcode" class="input" size="small" placeholder="商家自定义"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="商品描述">
                <el-input v-model="product.descr" class="input" size="small"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="关键词">
                <el-input v-model="product.keywords" class="input" size="small"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="封面图片">
                <el-upload
                  ref="upload"
                  action="/api/leju/admin/material/uploadAndSaveImg"
                  :on-success="handleSuccess"
                >
                  <el-button size="small" type="primary">点击上传</el-button>
                  <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                </el-upload>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-image style="width: 100px; height: 100px" :src="product.cover_img">
                <div slot="error" class="image-slot">
                  <i class="el-icon-picture-outline"></i>
                </div>
              </el-image>
            </el-col>
          </el-row>
          <el-row style="margin-top:8px">
            <el-col :span="8">
              <el-form-item label="是否上架">
                <el-switch
                  v-model="product.isshow"
                  active-color="#409EFF"
                  inactive-color="#DCDFE6"
                  :active-value="1"
                  :inactive-value="0"
                ></el-switch>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="新品推荐">
                <el-switch
                  v-model="product.isnew"
                  active-color="#409EFF"
                  inactive-color="#DCDFE6"
                  :active-value="1"
                  :inactive-value="0"
                ></el-switch>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="是否最热">
                <el-switch
                  v-model="product.ishot"
                  active-color="#409EFF"
                  inactive-color="#DCDFE6"
                  :active-value="1"
                  :inactive-value="0"
                ></el-switch>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row style="margin-top:8px">
            <el-col :span="8">
              <el-form-item label="进价">
                <el-input-number
                  v-model="product.price_in"
                  size="small"
                  :precision="2"
                  :step="1"
                  :min="0"
                ></el-input-number>
                <span>(单位分)</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="活动价">
                <el-input-number
                  v-model="product.price_now"
                  size="small"
                  :precision="2"
                  :step="1"
                  :min="0"
                ></el-input-number>
                <span>(单位分)</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="标价">
                <el-input-number
                  v-model="product.price_out"
                  size="small"
                  :precision="2"
                  :step="1"
                  :min="0"
                ></el-input-number>
                <span>(单位分)</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row style="margin-top:8px">
            <el-col :span="8">
              <el-form-item label="重量">
                <el-input-number
                  v-model="product.weight"
                  size="small"
                  :precision="2"
                  :step="1"
                  :min="0"
                ></el-input-number>
                <span>(单位克)</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="排序">
                <el-input-number v-model="product.sort" size="small" :step="1" :min="0"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="单位名称">
                <el-input
                  v-model="product.unit_name"
                  size="small"
                  class="input"
                  placeholder="比如:个/包/箱"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row style="margin-top:8px">
            <el-col :span="8">
              <el-form-item label="系列">
                <el-select v-model="product.seriesId" size="small" placeholder="请选择商品系列">
                  <el-option
                    v-for="item in seriesList"
                    :key="item.id"
                    :label="item.cname"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="商品分类">
                <el-checkbox-group v-model="product.kindIds" size="small">
                  <el-checkbox
                    v-for="item in kindList"
                    :label="item.id"
                    :key="item.id"
                  >{{item.ctitle}}</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="送货服务">
                <el-checkbox-group v-model="product.service_promise" size="small">
                  <el-checkbox :label="0">无</el-checkbox>
                  <el-checkbox :label="1">送货入户</el-checkbox>
                  <el-checkbox :label="2">上门安装</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 第二部分 -->
        <div class="step-sec" v-show="active==1">
          <el-row>
            <el-col :span="8">
              <el-form-item label="详情标题">
                <el-input v-model="product.detail_title" class="input" size="small"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="详情描述">
                <el-input v-model="product.detail_desc" class="input" size="small"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="20">
              <el-form-item label="添加sku">
                <div>颜色:</div>
                <el-checkbox-group v-model="checkSkuGather">
                  <el-checkbox
                    v-for="item in templateSkuGather"
                    :key="item.id"
                    :label="item.id"
                    :style="{color:item.color}"
                  >
                    {{item.color_text}}
                    <el-button type="text" size="small" @click="delCheckSku(item.id)">删除</el-button>
                  </el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="18">
              <el-form-item>
                <el-input
                  v-model="templateSku.color_text"
                  placeholder="请输入颜色:比如黑色"
                  class="input"
                  style="width:160px;margin-right:5px"
                  size="small"
                ></el-input>
                <el-input
                  v-model="templateSku.color"
                  placeholder="色值:比如#000"
                  class="input"
                  style="width:160px;margin-right:5px"
                  size="small"
                ></el-input>
                <el-button type="primary" @click="skuAdd" size="small">创建</el-button>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item>
                <el-button type="default" @click="createSku" size="small">生成</el-button>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="20">
              <el-form-item>
                <el-table :data="skuList" border stripe>
                  <el-table-column fixed label="#" type="index" width="50"></el-table-column>
                  <el-table-column label="颜色" prop="color_text" width="150"></el-table-column>
                  <el-table-column label="色值" prop="color" width="150"></el-table-column>
                  <el-table-column label="sku编码" width="220">
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.sku_code"
                        placeholder="自定义sku编码"
                        style="width:160px"
                        size="small"
                      ></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column label="价格" width="220">
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.price" style="width:160px" size="small"></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column label="库存" width="220">
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.count" style="width:160px" size="small"></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column fixed="right" label="操作" width="220">
                    <template slot-scope="scope">
                      <el-button
                        type="text"
                        size="small"
                        @click="delSku(scope.row.id)"
                        style="color:red"
                      >删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-form-item label="轮播图">
              <el-col :span="6">
                <el-upload
                  ref="bannerImg"
                  class="upload-demo"
                  action="/api/leju/admin/material/uploadImg"
                  :limit="4"
                  :on-exceed="handleExceed"
                  :on-success="handleBannerSucc"
                >
                  <el-button size="small" type="primary">点击上传</el-button>
                  <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb,且最多上传4张</div>
                </el-upload>
              </el-col>
              <el-col :span="18">
                <el-image
                  style="width: 100px; height: 100px"
                  v-for="item in product.imgs"
                  :src="item"
                  :key="item"
                >
                  <div slot="error" class="image-slot">
                    <i class="el-icon-picture-outline"></i>
                  </div>
                </el-image>
              </el-col>
            </el-form-item>
          </el-row>
          <el-form-item label="商品详情">
            <Tinymce v-model="product.content" upload-url="/api/leju/admin/material/uploadImg"></Tinymce>
          </el-form-item>
        </div>

        <!-- 第三部分 -->
        <div class="step-third" v-show="active==2">
          <el-row :gutter="30">
            <el-col :span="24">
              <el-form-item label="关联商品">
                <el-transfer v-model="productLink" :titles="['所有的商品','选中的商品']" :data="productList"></el-transfer>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="30">
            <el-col :span="24">
              <el-form-item label="备注信息">
                <el-input type="textarea" v-model="product.bak" placeholder="填写备注信息"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <!-- 第四部分button按钮 -->
        <div class="step-btn" style="text-align:center">
          <el-button type="default" size="small" v-show="active>0" @click="prestep">返回上一步</el-button>
          <el-button type="primary" size="small" v-show="active<2" @click="nextstep">{{nextBtnText}}</el-button>
          <el-button type="primary" size="small" v-show="active==2" @click="doSubmit">确定提交</el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import _ from "lodash";
import { regionDataPlus,CodeToText } from "element-china-area-data";
import brandApi from "@/api/product/brand";
import kindApi from "@/api/product/kind";
import seriesApi from "@/api/product/series";
import productApi from "@/api/product/index";
import Tinymce from "@/components/Tinymce";
export default {
  name: "productDetail",
  components: {
    Tinymce,
  },
  data() {
    return {
      active: 0,
      product: {
        cover_img: "",
        kindIds: [],
        service_promise: [],
        isshow: 1,
        imgs: [],
      },
      id: "",
      options: regionDataPlus,
      selectedCity: [],
      brandListAll: [],
      kindList: [],
      seriesList: [],
      productList: [], //关联商品的全部商品列表
      productLink: [], //选中的关联商品列表
      templateSku: {}, //临时的单个sku颜色/属性
      templateSkuGather: [], //临时的sku颜色/属性集合
      checkSkuGather: [], //选中的sku颜色/属性集合
      skuList: [], //sku的表格集合
      rules: {
        gname: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
          {
            min: 3,
            max: 15,
            message: "长度在 3 到 15 个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.id = this.$route.params.id;
    this.getBrandList();
    this.getKindList();
    this.getseriesList();
    this.getproductList();
    if (this.id) {
      this.getproductDetail(); //根据id来初始化详细页
    }
    //初始化城市信息
    this.praseCity(this.selectedCity)
  },
  computed: {
    nextBtnText() {
      //修改btn上的文字信息
      var text = "";
      switch (this.active) {
        case 0:
          text = "下一步,填写库存信息";
          break;
        case 1:
          text = "下一步,相关商品添加";
          break;
        default:
          break;
      }
      return text;
    },
  },
  methods: {
    prestep() {
      //按钮返回一步
      this.active--;
    },
    nextstep() {
      //前进一步
      this.active++;
    },
    handleChange(value) {
      //城市选择
      console.log(value);
      this.praseCity(value)
    },
    praseCity(value){
      this.product.origin_code=value.join(',')
      var text='';
      for(var i=0;i<value.length;i++){
        text +=','+ CodeToText[value[i]]
      }
       // text  ',xx,xx,xx';
      text=text.substr(1);// 从下表为1开始 截取字符串
      this.product.origin_city=text
    },
    getproductDetail() {
      //获取商品明细,注意转换格式
      productApi
        .productDetail({
          id: this.id,
        })
        .then((res) => {
          var pro = res.data;

          pro.imgs = pro.imgs.split(",");
          
          if (pro.kindIds.indexOf(",") != -1) {
            pro.kindIds = pro.kindIds.split(",");
          }
          
          this.selectedCity =pro.origin_code.split(",")
          
          this.skuList = pro.skuList;
          
          this.productLink=pro.link1.split(',')
 
          this.product = pro;
        });
    },
    getBrandList() {
      //品牌列表
      brandApi.brandListAll().then((res) => {
        this.brandListAll = res.data;
      });
    },
    getKindList() {
      //分类列表
      kindApi.kindList().then((res) => {
        this.kindList = res.data;
      });
    },
    getseriesList() {
      //系列列表
      seriesApi.seriesList().then((res) => {
        this.seriesList = res.data;
      });
    },
    getproductList() {
      //商品列表,展示在关联商品的全部商品类
      productApi.productList().then((res) => {
        var list = res.data.list;
        list.forEach((item) => {
          this.productList.push({
            key: item.id,
            label: item.gname,
          });
        });
      });
    },
    handleSuccess(response) {
      this.product.cover_img = response.ossUrl;
      this.$refs.upload.clearFiles(); //清空已上传的文件列表
    },
    skuAdd() {
      //将单个的sku颜色/属性push到templateSkuGather列表中
      var objSku = _.clone(this.templateSku);
      this.templateSkuGather.push({
        id: new Date().getTime(),
        ...objSku,
      });
      this.templateSku = {};
    },
    delCheckSku(id) {
      //删除sku
      var index = this.templateSkuGather.findIndex((item) => {
        item.id == id;
      });
      this.templateSkuGather.splice(index, 1);
    },
    createSku() {
      this.skuList = this.templateSkuGather.filter((item) =>
        this.checkSkuGather.includes(item.id)
      );
    },
    delSku(id) {
      var index = this.skuList.findIndex((item) => {
        item.id == id;
      });
      this.skuList.splice(index, 1);
    },
    handleExceed(files, fileList) {
      //图片超过上传数量
      this.$message("已到达图片上传数量,无法上传");
    },
    handleBannerSucc(response, file, fileList) {
      this.product.imgs.push(response.ossUrl);
      this.$refs.bannerImg.clearFiles();
    },
    doSubmit() {
      //表单提交
      this.$refs.form.validate((valid) => {
        if (valid) {
          //将skuList转换为需要提交的格式
          for (var i = 0; i < this.skuList.length; i++) {
            this.product["skuList[" + i + "]"] = this.skuList[i];
          }

          //关联商品的提交格式(字符串形式)
          this.product.link1 = this.productLink.join(",");
       
          productApi.saveOrUpdate(this.product).then((res) => {
            if (res.code == "success") {
              this.$message.success("提交成功");
              this.$router.push({ name: "productList" });
            } else {
              this.$message.error("数据上传错误");
            }
          });
        } else {
          this.$message.warning("请注意表单验证");
        }
      });
    },
  },
};
</script>
<style lang='scss' scoped>
.product-add-main {
  .step-bar {
    width: 70%;
    margin-left: 15%;
    margin-top: 35px;
  }
  .el-card {
    margin: 50px;
    padding-top: 20px;
    .input {
      width: 220px;
    }
  }
}
</style>